package com.utry.license.server.exception;

import com.utry.license.common.base.BaseException;
import com.utry.license.common.base.BaseResult;
import com.utry.license.common.base.ErrorEnum;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @description 全局异常拦截器
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2019/8/5 8:50
 */
@ControllerAdvice(basePackages = "com.utry.license.server.api")
public class GlobalExceptionHandler {

    /**
     * 接口参数校验异常拦截
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public  BaseResult baseResult(MethodArgumentNotValidException e){

        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        return BaseResult.build(ErrorEnum.PARAMETER_ILLEGAL.getCode(),defaultMessage);
    }

    /**
     * 自定义业务异常拦截
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BaseException.class)
    public BaseResult baseResult(BaseException e){

        return BaseResult.build(e);
    }

    /**
     * 其他异常拦截
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseResult baseResult(Exception e){

        return BaseResult.build(ErrorEnum.SYSTEM_ERROR.getCode(),e.getMessage());
    }

}
